﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Net;
using System.Net.Sockets;
using System.Text;
using System.Threading.Tasks;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;

namespace SocketClient
{
    /// <summary>
    /// MainWindow.xaml 的交互逻辑
    /// </summary>
    public partial class MainWindow : Window
    {
        private IPAddress MyIP { get; set; }
        private int Port { get; set; }
        public TcpClient TcpClient { get; set; }
        public MainWindow()
        {
            InitializeComponent();
            StopBtn.IsEnabled = false;
        }

        private void ConnectBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                MyIP = IPAddress.Parse(IpAddressBox.Text);
                Port = int.Parse(PortBox.Text);
                TcpClient = new TcpClient();
                TcpClient.Connect(MyIP, Port);

                MessageInfo.Inlines.Add(new LineBreak());
                MessageInfo.Inlines.Add(new Run("连接成功"));

                ConnectBtn.IsEnabled = false;
                StopBtn.IsEnabled = true;
            }
            catch (Exception ex)
            {
                MessageInfo.Inlines.Add(new LineBreak());
                MessageInfo.Inlines.Add(new Run("连接失败：" + ex.Message));
            }
        }

        private void SendBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                string message = SendMessage.Text;
                MessageInfo.Inlines.Add(new LineBreak());
                MessageInfo.Inlines.Add(new Run("发送：“" + message + "”"));
                NetworkStream networkStream = TcpClient.GetStream();
                byte[] byteArray = Encoding.UTF8.GetBytes(message);
                // 发送字节数组 
                networkStream.Write(byteArray, 0, byteArray.Length);
            }
            catch (Exception ex)
            {
                MessageInfo.Inlines.Add(new LineBreak());
                MessageInfo.Inlines.Add(new Run("连接失败：" + ex.Message));
            }
        }

        private void StopBtn_Click(object sender, RoutedEventArgs e)
        {
            try
            {
                TcpClient.Close();
                TcpClient.Dispose();

                ConnectBtn.IsEnabled = true;
                StopBtn.IsEnabled = false;
            }
            catch (Exception ex)
            {
                MessageInfo.Inlines.Add(new LineBreak());
                MessageInfo.Inlines.Add(new Run("连接失败：" + ex.Message));
            }
        }
    }
}
